package com.lyfx.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lyfx.common.to.es.CourseModel;
import com.lyfx.common.utils.R;
import com.lyfx.search.config.ElasticSearchConfig;
import com.lyfx.search.contant.Esconstant;
import com.lyfx.search.feign.LyFeignService;
import com.lyfx.search.service.CourseSearchService;
import com.lyfx.search.vo.AttrResponseVo;
import com.lyfx.search.vo.SearchParms;
import com.lyfx.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.CardinalityAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.ParsedCardinality;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.collapse.CollapseBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author lsy
 * @create 2020-08-01-12:05
 */
@Service
public class CourseSearchServiceImpl implements CourseSearchService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    LyFeignService lyFeignService;
    @Override
    public SearchResult search(SearchParms parms) {
    //动态构建出查询所需要的dsl语句
        SearchResult result = null;

        //准备检索请求
        SearchRequest searchRequest = buildSearchRequrest(parms);
        try {
            //执行检索请求
            SearchResponse response = restHighLevelClient.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);

            //分析相应数据封装成需要的格式
            result = buildSearchResult(response,parms);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 构建结果数据
     */
    private SearchResult buildSearchResult(SearchResponse response,SearchParms parms) {
        SearchResult searchResult = new SearchResult();
        //所有课程
        SearchHits hits = response.getHits();
        List<CourseModel> models = new ArrayList<>();
        if (hits.getHits()!=null && hits.getHits().length>0){
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                CourseModel courseModel = JSON.parseObject(sourceAsString, CourseModel.class);
                if (!StringUtils.isEmpty(parms.getKeyword())){
                    HighlightField name = hit.getHighlightFields().get("name");
                    String string = name.getFragments()[0].string();
                    courseModel.setName(string);
                }
                models.add(courseModel);
            }
        }
        searchResult.setCourses(models);

//        课程涉及到的属性信息
        List<SearchResult.AttrVo> attrs = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //得到属性id
            long attrId = bucket.getKeyAsNumber().longValue();
            //属性名字
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            //属性值
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                String keyAsString = item.getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrs.add(attrVo);
        }
        searchResult.setAttrs(attrs);
//        课程涉及到的分类信息
        ParsedLongTerms catlog_agg = response.getAggregations().get("catlog_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket bucket : catlog_agg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            //分类 id
            catalogVo.setCategoryId(bucket.getKeyAsNumber().longValue());
            //分类 名字
            ParsedStringTerms catlog_name_agg = bucket.getAggregations().get("catlog_name_agg");
            String keyAsString = catlog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCategoryName(keyAsString);
            catalogVos.add(catalogVo);
        }

        searchResult.setCatalogVos(catalogVos);
//        分页信息，页码
        searchResult.setPageNum(parms.getPageNum());
//        总记录数,聚合的总数量
        ParsedCardinality count = response.getAggregations().get("count");
        long total = count.getValue();
        searchResult.setTotal(total);
//        总页码  计算 11/2 = 5 .. 1
        int totalPages = (int)total % Esconstant.COURSE_PAGESIZE == 0 ? (int)total/Esconstant.COURSE_PAGESIZE : ((int)total/Esconstant.COURSE_PAGESIZE+1);
        searchResult.setTotalPages(totalPages);
        List<Integer> pageNavs= new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);


        //构建面包屑导航功能
        if(parms.getAttrs()!=null&&parms.getAttrs().size()>0){
            List<SearchResult.CrumbVo> crumbVos = parms.getAttrs().stream().map(attr -> {
                SearchResult.CrumbVo crumbVo = new SearchResult.CrumbVo();
                ////attr = 1_初级:高级
                String[] s = attr.split("_");
                crumbVo.setCrumbValue(s[1]);
                R attrsInfo = lyFeignService.getAttrsInfo(Long.parseLong(s[0]));
                searchResult.getAttrIds().add(Long.parseLong(s[0]));//属性的显示消失
                if((Integer)attrsInfo.get("code") == 0){
                    AttrResponseVo data = attrsInfo.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    crumbVo.setCrumbName(data.getAttrName());
                }else {
                    crumbVo.setCrumbName(s[0]);
                }
                //拿到所有条件，去掉当前
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr, "UTF-8");
                    //浏览器对空格的处理
                    encode=encode.replace("+", "%20");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = parms.get_queryString().replace("&attrs="+encode, "");
                crumbVo.setLink("http://search.lyfx.com/all-class?"+replace);
                return crumbVo;
            }).collect(Collectors.toList());
            searchResult.setCrumbs(crumbVos);
        }

        return searchResult;
    }

    /**
     * 构建检索请求
     * 模糊匹配，过滤（按照三级分类条件，属性条件），排序，分页，高亮，聚合分析
     */
    private SearchRequest buildSearchRequrest(SearchParms parms) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //1.查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //  must  模糊匹配，
        if(!StringUtils.isEmpty(parms.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("name", parms.getKeyword()));
        }
        //filter 匹配 （按照三级分类条件）
        if(!StringUtils.isEmpty(parms.getCategory())){
            /**
             * 1.category=f1000381
             */
            if(isCatlogStr(parms.getCategory())){
                String a = parms.getCategory();
                String str = splitCategoryStr(parms.getCategory());
                if(!StringUtils.isEmpty(str) && isNumeric(str)){
                    boolQuery.filter(QueryBuilders.termQuery("categoryId",Long.parseLong(str)));
                }
            }
        }
        //filter 匹配 （属性条件）
        if(parms.getAttrs()!=null && parms.getAttrs().size()>0){
            for (String attrStr : parms.getAttrs()) {
                BoolQueryBuilder nestedboolQuery = QueryBuilders.boolQuery();
                //attr = 1_初级:高级
                String[] s = attrStr.split("_");
                String attrId = s[0];
                String[] attrvalues = s[1].split(":");
                nestedboolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedboolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrvalues));
                //每一个都生成嵌入式查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedboolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }

        //把所有的条件进行封装
        sourceBuilder.query(boolQuery);
        //2.排序，分页，高亮
        //2.1排序
        if(!StringUtils.isEmpty(parms.getSort())){
            String sort = parms.getSort();
            //sort=hot_desc/asc
            String[] s = sort.split("_");
            sourceBuilder.sort(s[0], s[1].equalsIgnoreCase("asc")?SortOrder.ASC:SortOrder.DESC);
        }
        //2.2分页 (pageNum-1)*pageSize
        sourceBuilder.from((parms.getPageNum()-1)*Esconstant.COURSE_PAGESIZE);
        sourceBuilder.size(Esconstant.COURSE_PAGESIZE);
        //2.3高亮 只有在模糊匹配的时候才做
        if(!StringUtils.isEmpty(parms.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("name");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }
        //3.聚合分析
        //3.1三级分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catlog_agg").field("categoryId").size(50);
        catalog_agg.subAggregation(AggregationBuilders.terms("catlog_name_agg").field("categoryName").size(1));
        sourceBuilder.aggregation(catalog_agg);
        //3.2统计数量聚合
        CardinalityAggregationBuilder field = AggregationBuilders.cardinality("count").field("courseId");
        sourceBuilder.aggregation(field);
        //3.3属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        //聚合所有的attrid
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        //聚合分析出attrid对应的name
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        //聚合分析出attrid所有对应的value
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attr_agg);
        //4。按照courseId 对结果进行过滤
        sourceBuilder.collapse(new CollapseBuilder("courseId"));
        System.out.println("构建的dsl语句"+sourceBuilder.toString());
        SearchRequest searchRequest = new SearchRequest(new String[]{Esconstant.COURSE_INDEX},sourceBuilder);
        return searchRequest;
    }

    /**
     * 分割传来的菜单参数
     */
    private String splitCategoryStr(String a) {
        String str="";
        try {
            str = a.split("f1000")[1].trim();
        }catch (Exception e){
            str = "";
        }
        return str;
    }

    /**
     * 判断字符串是否是数字
     */
    private  boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }
    /**
     *判断菜单格式
     */
    private  boolean isCatlogStr(String str){
        String pat = "\\bf1000[0-9]*";
        Pattern pattern = Pattern.compile(pat);
        return pattern.matcher(str).matches();
    }


}
